<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>注册页</title>
	</head>
	<body>
		<button type="button" onclick="javascript:location.href='/login.html';">返回登录</button><br>
		用户名：<input onblur="check()" id="uname" type="text"><br>
		密码：<input onblur="check_pwd()" id="password" type="password"><br>
		邮箱：<input id="email" type="email"><br>
		电话：<input id="phone" type="text"><br>
		姓名：<input id="username" type="text"><br>
		性别：<input type="radio" name="gender" id="man" value="1" /><label for="man">男</label>
				<input type="radio" name="gender" id="woman" value="0" /><label for="woman">女</label>
				<input type="radio" checked name="gender" id="unkonw" value="-1" /><label for="unkonw">保密</label><br>
		<button type="button" onclick="register()">注册</button>
		<script>
			//判断用户名是否重复
			function check(){
				let _name = uname.value;
				
				if(!_name){
					return;
				}else{
					//获取对象
					let xhr = new XMLHttpRequest();
					//接收响应，打开监听
					xhr.onreadystatechange = function(){
						if(xhr.readyState == 4 && xhr.status == 200){
							let data = xhr.responseText;
							if(data == 1){
								alert('用户名已存在');
								//页面刷新
								location.reload();
							}
						}
					};
					//打开连接
					xhr.open('GET',`/pro/v1/getUname/${_name}`,true);
					//发送请求
					xhr.send();
				}
			}
			
			//注册
			function register(){
				let _uname = uname.value;
				let _password = password.value;
				let _email = email.value;
				let _phone = phone.value;
				let _username = username.value;
				let sex = -1;
				if(man.checked){
					sex = 1;
				}else if(woman.checked){
					sex = 0;
				}else{
					sex = -1;
				}
				
				//非空判断
				if(!_uname){
					return alert('用户名不能为空');
				}
				if(!_password){
					return alert('用户名不能为空');
				}
				if(!_email){
					return alert('邮箱不能为空');
				}
				if(!_phone){
					return alert('联系方式不能为空');
				}
				if(!_username){
					return alert('姓名不能为空');
				}
				
				//获取对象
				let xhr = new XMLHttpRequest();
				//接收响应，打开监听
				xhr.onreadystatechange = function(){
					if(xhr.readyState == 4 && xhr.status == 200){
						let data = xhr.responseText;
						// console.log(data);
						if(data == 1){
							alert('注册成功');
							location.href = '/login.html';
						}else{
							alert('注册失败');
						}
					}
				};
				//打开连接
				xhr.open('POST','/pro/v1/reg',true);
				//设置头信息
				xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
				//设置主体数据
				let data = `uname=${_uname}&upwd=${_password}&email=${_email}&phone=${_phone}&user_name=${_username}&gender=${sex}`;
				//发送请求
				xhr.send(data);
			}
			
		</script>
	</body>
</html>
